/**
 * 
 */
package de.fsujena.chat_pi.server.room;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

/**
 * @author Erik Hebestreit
 *
 */
public class RoomManagement {
	public HashMap<String,Room> rooms = new HashMap<String,Room>();
	public String filename = "roomMap.dat";

	/**
	 * 
	 */
	public RoomManagement() {
		loadRoomMap();
	}

	@SuppressWarnings("unchecked")
	public boolean loadRoomMap() {
		// load existing users from database
		File file = new File(filename);
		
		if (file.exists()) {
			try {
				FileInputStream f = new FileInputStream(file);
				ObjectInputStream s = new ObjectInputStream(f);
				Object inputObject = s.readObject();
				
				if (inputObject instanceof HashMap<?,?>)
					this.rooms = (HashMap<String,Room>) inputObject;
				
				s.close();
				
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				return false;
			}
		} else {
			System.err.println("Failed to load room map.");
			return false;
		}
	}
	
	public boolean saveUserMap() {
		File file = new File(filename);
		FileOutputStream f;
		ObjectOutputStream s;
		
		try {
			f = new FileOutputStream(file);
			s = new ObjectOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
		try {
			s.writeObject(this.rooms);
			s.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
		return true;
	}

}
